﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Windows.Forms;

namespace AUCS
{
    class FileManager
    {
        XmlDocument fileXMLDoc;
        NativeTreeView fileTreeView;

        public FileManager(XmlDocument XMLDoc, NativeTreeView nTreeView)
        {
            fileXMLDoc = XMLDoc;
            fileTreeView = nTreeView;
        }

        public void populateTreeView(string hostname, int port)
        {
            if (fileXMLDoc.HasChildNodes)
            {
                fileTreeView.Nodes.Clear();
                TreeNode server = fileTreeView.Nodes.Add(hostname+":"+port);
                server.ImageKey = "FolderIcon.png";
                server.SelectedImageKey = "FolderOpenIcon.png";

                recursiveChildSearch(fileXMLDoc.ChildNodes, server);
            }
        }

        //Recursive function; Cycles through all XMLNodes in a list and calls itself on their child list in turn. 
        //Also calls XMLNodetoTreenode on each node
        void recursiveChildSearch(XmlNodeList target, TreeNode parent)
        {
            foreach (XmlNode node in target)
            {
                TreeNode targetChild = parent.Nodes.Add(node.Name);
                XMLNodetoTreenode(node, targetChild);
                recursiveChildSearch(node.ChildNodes, targetChild);
            }
        }

        //Processes an XMLNode and sets the Treenode's Images to reflect the node's type
        private void XMLNodetoTreenode(XmlNode xmNode, TreeNode trNode)
        {
            switch (xmNode.Attributes["type"].Value)
            {
                case "Folder":
                    trNode.ImageKey = "FolderIcon.png";
                    trNode.SelectedImageKey = "FolderOpenIcon.png";
                    break;
                case "TXT":
                    trNode.ImageKey = "TXTFileIcon.png";
                    trNode.SelectedImageKey = "TXTFileIcon.png";
                    break;
                default:
                    trNode.ImageKey = "FileIcon.png";
                    trNode.SelectedImageKey = "FileIcon.png";
                    break;
            }
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
